package dataStructure.greedy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

/**
 * @author lhn
 * @date 2024-09-11 15:36
 */

public class GreedyTest {
    public static void main(String[] args) {
        // 创建广播电台，放入到Map中
        HashMap<String, HashSet<String>> broadcast = new HashMap<String, HashSet<String>>();

        HashSet<String> hashSet1 = new HashSet<String>();
        hashSet1.add("北京");
        hashSet1.add("上海");
        hashSet1.add("天津");
        broadcast.put("K1", hashSet1);

        HashSet<String> hashSet2 = new HashSet<String>();
        hashSet2.add("广州");
        hashSet2.add("北京");
        hashSet2.add("深圳");
        broadcast.put("K2", hashSet2);

        HashSet<String> hashSet3 = new HashSet<String>();
        hashSet3.add("成都");
        hashSet3.add("上海");
        hashSet3.add("杭州");
        broadcast.put("K3", hashSet3);

        HashSet<String> hashSet4 = new HashSet<String>();
        hashSet4.add("上海");
        hashSet4.add("天津");
        broadcast.put("K4", hashSet4);

        HashSet<String> hashSet5 = new HashSet<String>();
        hashSet5.add("杭州");
        hashSet5.add("大连");
        broadcast.put("K5", hashSet5);

        HashSet<String> allAreas = new HashSet<String>();
        allAreas.add("北京");
        allAreas.add("上海");
        allAreas.add("天津");
        allAreas.add("广州");
        allAreas.add("深圳");
        allAreas.add("成都");
        allAreas.add("杭州");
        allAreas.add("大连");

        System.out.println(
                greedyAlgorithm(broadcast, allAreas)
        );

    }

    public static ArrayList<String> greedyAlgorithm(HashMap<String, HashSet<String>> broadcast, HashSet<String> allAreas) {
        ArrayList<String > selects = new ArrayList<String>();
        HashSet<String> tempSet = new HashSet<String>();

        while (allAreas.size() > 0 ) {
            String maxKey = null;

            for (String key : broadcast.keySet()
                 ) {
                tempSet.clear();
                HashSet<String> areas = broadcast.get(key);
                tempSet.addAll(areas);
                tempSet.retainAll(allAreas);
                if (
                        tempSet.size() > 0 &&
                                (broadcast.get(maxKey) == null || tempSet.size() > broadcast.get(maxKey).size())
                ) {
                    maxKey = key;
                }
            }

            if (maxKey != null) {
                selects.add(maxKey);
                allAreas.removeAll(broadcast.get(maxKey));
            }
        }

        return selects;
    }

}
